<template>
  <a-tree
    v-model:expandedKeys="expandedKeys"
    autoExpandParent
    showLine
    :tree-data="treeNodeData"
    :fieldNames="fieldNames"
  >
    <template #title="{ showToolBtn, id: treeKey, text }">
      <a-dropdown :trigger="['contextmenu']">
        <span :title="treeKey">
          <EyeInvisibleOutlined
            v-if="!showToolBtn"
            @click="() => toggleToolBtnWrapper(true, treeKey)"
          />
          <EyeOutlined v-else @click="() => toggleToolBtnWrapper(false, treeKey)" />
          {{ text }}
        </span>
      </a-dropdown>
    </template>
  </a-tree>
</template>

<script setup lang="ts">
import { EyeOutlined, EyeInvisibleOutlined } from '@ant-design/icons-vue'
import { useDesignerStore } from '@/stores/designerStore'
import { storeToRefs } from 'pinia'
import type { TreeProps } from 'ant-design-vue'

const designerStore = useDesignerStore()
const { designCompList, currentAddCompInstanceId, designCompMapSize } = storeToRefs(designerStore)
const { toggleToolBtn, findAnssertIds } = designerStore
const expandedKeys = ref<string[]>([])
const treeNodeData = ref<TreeProps['treeData']>([])
const fieldNames: TreeProps['fieldNames'] = {
  title: 'text',
  key: 'id'
}

function toggleToolBtnWrapper(showToolBtn: boolean, id: string) {
  toggleToolBtn(showToolBtn, id)
}
watch(
  designCompList,
  (newList) => {
    treeNodeData.value = [...newList] as unknown[] as TreeProps['treeData']
  },
  { deep: true, immediate: true }
)
watch([currentAddCompInstanceId, designCompMapSize], ([newCurrentAddCompInstanceId]) => {
  const assertIds = findAnssertIds(newCurrentAddCompInstanceId)
  if (!assertIds || assertIds.length === 0) {
    return
  }
  expandedKeys.value = Array.from(new Set<string>([...expandedKeys.value, ...assertIds]))
})
</script>

<style scoped></style>
